#ifndef CLIENTSOCKET_H
#define CLIENTSOCKET_H
#include <QObject>
#include <QThread>
#include <QAbstractSocket>
#include <QQueue>
#include <QMutex>
#include <QRegExp>

class QTcpSocket;
class ConfDeal;

struct DownCmd
{
    DownCmd() : devID(0),pID(0),val(0.0)
    {

    };

    DownCmd(int _devID,int _pID, qreal _val)
        : devID(_devID),pID(_pID),val(_val)
    {

    };

    int devID;
    int pID;
    qreal val;
};

class ClientSocket
        : public QThread
{
    Q_OBJECT
public:
    ClientSocket(QObject *parent = Q_NULLPTR);
    ~ClientSocket();

    void initIpForView();
protected:
    virtual void run();
private:
    bool initTcpSocket();
    bool destroyTcpSocket();
    bool connectMyHost();
    bool disconnectMyHost();
    unsigned int getUsec();
    unsigned int getSec();
    QString getDTStr(int sc, int msc);
    int code(const unsigned char *buff, const int len, unsigned char *outbuf);
    int uncode(const unsigned char *buff, int len, unsigned char *outbuf);
    void doCmd();
    bool getCmd(DownCmd &cmd_);
    void addCmd(DownCmd cmd_);
    bool downcmdsEmpty();
    void Control(int devID,int pID,qreal val);
signals:
    void addDev(QVariant devID,QVariant devType,QVariant name, QVariant desc);
    void addPInfo(QVariant devID,QVariant pID,QVariant name,QVariant desc,QVariant pType,QVariant val);
    void PValue(QVariant devID,QVariant pID,QVariant dtime, QVariant val);
    void ipLinkSuccess(QVariant ip_);
public slots:
    void setPValue(int devID,int pID,qreal val);
    void onIpConf(QString ip_);
    void checkLink();
    void checkForReadyRead();
private slots:
    void sockeError(QAbstractSocket::SocketError error);
    void readData();
    void readCache(const unsigned char *bufdata,int buflen);
private:
    bool running;
    ConfDeal *ptr_ConfDeal;
    QString m_ip;
    int m_port;
    QRegExp rx;
    QTcpSocket *m_csocket;
    bool linking;
    bool ativity;
    unsigned int ativityCheck;
    QQueue<DownCmd> downcmds;
    QMutex downcmds_mutex;
    int limitSize;
};

#endif // CLIENTSOCKET_H
